//aapt是 Android Asset Packaging Tool,可以用来获取Apk信息 aapt d badging file.apk
var spawn = require('child_process').spawn;
const os = require('os');
var path = require('path');

var aapt = __dirname + '/xbin/aapt'
//先判断os platform,platform调用不同platform的aapt二进制可执行文件
var platform = os.platform();
if(platform == "darwin"){
    aapt = __dirname + '/xbin/aapt_23.0.1_mac'
}if(platform == "linux"){
    aapt = __dirname + '/xbin/aapt_19.0.1_linux'
}if(platform == "win32"){
    aapt = __dirname + '/xbin/aapt_19.0.1_win'
}

/**
 * 获取包名、应用名、版本号、版本名
 * @param filePath apk文件的路径
 * @returns {Promise}
 */
function getBasicInfo(filePath,channel_id) {
    return new Promise(function (resolve, reject) {
        //捕获标准输出
        dump = spawn(aapt, ['d', 'badging', filePath]);
        dump.stdout.on('data', function (data) {

            //把不规则的字符串变为一行一行的
            var str = data.toString();
            var array = [];
            var source = str.split('\n');
            for (var i = 0; i < source.length; i++) {
                var item = source[i];
                //第一行有很多重要信息,但是这些信息不规则,对第一行单独做处理
                if (i < 1) {
                    var index = item.indexOf(' ');
                    var arr = item.split(' ');
                    for (var tmpIn of arr)
                        array.push(tmpIn);
                } else {
                    array.push(item);
                }
            }

            //筛选出有用的数据
            var package_nameLable = "name="; //包名
            var version_codeLable = "versionCode="; //版本号
            var version_nameLable = "versionName="; //版本名
            var nameLable = "application-label:"; //应用名
            var nameLable2 = 'application-label-zh-CN:';//优先
            var appInfo = {package_name: "", version_code: "", version_name: "", app_name: "",channel_id:channel_id}

            for (var item of array) {
                if (item.indexOf(package_nameLable) == 0) {
                    appInfo.package_name = item.substring(package_nameLable.length + 1, item.length - 1);
                } else if (item.indexOf(version_codeLable) == 0) {
                    appInfo.version_code = item.substring(version_codeLable.length + 1, item.length - 1);
                } else if (item.indexOf(version_nameLable) == 0) {
                    appInfo.version_name = item.substring(version_nameLable.length + 1, item.length - 1);
                } else if (item.indexOf(nameLable) == 0) {
                    appInfo.app_name = item.substring(nameLable.length + 1, item.length - 1);
                }   else if (item.indexOf(nameLable2) == 0) {
                    appInfo.app_name = item.substring(nameLable2.length + 1, item.length - 1);
                }
            }
            resolve(appInfo);
        });

        //捕获标准错误输出
        dump.stderr.on('data', function (data) {
            console.log("解析apkError(清单文件):"+data)
            reject(data);
        });

        dump.stdout.on('end', function () {
            console.log('解析apk结束(清单文件)!');
        });

    });
}

/**
 * 获取渠道值
 * @param filePath apk文件的路径
 * @returns {Promise}
 */
function getChannelName(filePath) {
    return new Promise(function (resolve, reject) {
        //获取清单文件信息
        // aapt dump xmlstrings youyan.apk AndroidManifest.xml
        //UMENG_CHANNEL=fir.im
        dump = spawn(aapt, ['dump', 'xmlstrings', filePath, 'AndroidManifest.xml']);

        dump.stdout.on('data', function (data) {
            var str = data.toString();
            var array = [];
            var source = str.split('\n');

            //拆分为字符数组
            var channelKeyName = "UMENG_CHANNEL"
            for (var i = 0; i < source.length; i++) {
                var line = source[i];
                var index = line.lastIndexOf(channelKeyName);
                if (index > 0) { //找到了渠道Key
                    //下一行为渠道Value
                    var nextLine = source[i + 1];
                    resolve(nextLine.substring(nextLine.lastIndexOf(' '), nextLine.length).replace(/\s/g, ""))
                    break;
                }
            }
            //该apk没有渠道字段
            resolve("0")
        });

        //捕获标准错误输出
        dump.stderr.on('data', function (data) {
            console.log("解析apkError(渠道):"+data)
            reject(data);
        });

        dump.stdout.on('end', function () {
            console.log('解析apk结束（渠道）!');
        });


    });
}

var functions = {
    getApplicationInfo(apkPath){
        return getChannelName(apkPath).then(function (channel_id) {
            return getBasicInfo(apkPath,channel_id);
        });
    }
}

module.exports = functions;
